﻿using csLTDMC;
using InspectionMAC.Forms;
using InspectionMAC.Function;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InspectionMAC.SystemThread
{
    class MarginThread
    {
        public static bool RecordLocation_Flowrec = false;
        public static Thread RecordLocationFlow_Thread = null;
        public static int iRecordLocation_Step = 0;

        public static bool RecordLocation_Stop = false;

        public static bool IsAlarmTriggered = false;
        public static void RecordLocation_Thread()
        {
            RecordLocation_Flowrec = true;
            RecordLocationFlow_Thread = new Thread(RecordLocationFlowThread);
            RecordLocationFlow_Thread.IsBackground = true;
            RecordLocationFlow_Thread.Start();
            IsAlarmTriggered = false;
            iRecordLocation_Step = 10;
        }
        private static void RecordLocationFlowThread(object obj)
        {
            while (RecordLocation_Flowrec)
            {
                switch (iRecordLocation_Step)
                {
                    case 0:

                        break;

                    case 10:
                        if (DIO_Thread.Di[6] == 0)
                        {
                            if (!IsAlarmTriggered )
                            {
                                IsAlarmTriggered = true;
                                // 触发报警事件
                                DIO_Thread.Do[8] = 1;
                                MacTestForm.macTestForm.Invoke(new Action(() =>
                                {
                                    MacTestForm.macTestForm.ShowAlarmForm("缺料报警!");
                                    MacTestForm.macTestForm.AddLog("缺料！");
                                    MacTestForm.macTestForm.FeedAxisStopBtn_Click(null, EventArgs.Empty);
                                    MacTestForm.macTestForm.FixedAxisStopBtn_Click(null, EventArgs.Empty);
                                    
                                }));
                            }
                        }
                        break;
                }
            }
        }

        public static void StopRecordLocationThread()
        {
            RecordLocation_Flowrec = false;
            RecordLocation_Stop = true;

            // 等待线程安全结束
            if (RecordLocationFlow_Thread != null && RecordLocationFlow_Thread.IsAlive)
            {
                RecordLocationFlow_Thread.Join(1000); // 等待1秒
            }

            RecordLocationFlow_Thread = null;
            iRecordLocation_Step = 0; // 重置状态
        }

    }
}
